var express = require('express');
const { listModel, addressModel, shopListModel } = require('../model/model');
var router = express.Router();
var alipaySdk = require("./alipay")
var AlipayFormData = require("alipay-sdk/lib/form").default

/* GET home page. */
router.get('/getlist', async (req, res, next) => {
    let data = await listModel.find()
    res.send({
        data,
        code: 200
    })
});

router.get('/getAddress', async (req, res, next) => {
    let data = await addressModel.find()
    res.send({
        data,
        code: 200
    })
});

router.post('/addAddress', async (req, res, next) => {
    addressModel.create(req.body)
    res.send({
        code: 200
    })
});

router.post('/delAddress', async (req, res, next) => {
    await addressModel.deleteOne({ _id: req.body._id })
    res.send({
        code: 200
    })
});
router.post('/updateAddress', async (req, res, next) => {
    let _id=req.body._id
    await addressModel.updateMany({ isdefault: true }, { $set: { isdefault: false } });
    await addressModel.updateOne({ _id: _id }, { $set: { isdefault: true } });
    let data = await addressModel.findOne({_id:_id})
    res.send({
        data,
        code: 200
    })
});
router.post('/addcate',async(req,res)=>{
    await shopListModel.create(req.body)
    res.send({
        code:200
    })
})
router.post('/shopping', async (req, res, next) => {
    (async () => {
        let formData = new AlipayFormData();
        let data = req.body.data
        let Did=data._id+String(Date.now())
        formData.setMethod('get');
        formData.addField('returnUrl', 'exp://192.168.13.227:8081');
        formData.addField('bizContent', {
            out_trade_no: Did,//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
            product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
            total_amount: data.price * req.body.num,// 订单总金额
            subject: data.name,// 订单描述
            body: data.detail,// 商品描述
        })
        const result = await alipaySdk.exec(
            'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
            {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
            { formData: formData }// result为可以跳转支付链接的url
        )
        res.json({ url: result })
    })()
});



module.exports = router;
